package com.explorati.interview.interview.Thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test3Business {

	private String flag = "A";
	private Lock lock = new ReentrantLock();
	private Condition cA = lock.newCondition();
	private Condition cB = lock.newCondition();
	private Condition cC = lock.newCondition();

	public void printB() {
		try {
			lock.lock();
			if (!flag.equals("A")) {
				cA.await();
			}
			System.out.println(Thread.currentThread().getName());
			Thread.sleep(1000);
			flag = "B";
			cB.signal();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public void printA() {
		try {
			lock.lock();
			if (!flag.equals("B")) {
				cB.await();
			}
			System.out.println(Thread.currentThread().getName());
			Thread.sleep(1000);
			flag = "C";
			cC.signal();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public void printC() {
		try {
			lock.lock();
			if (!flag.equals("C")) {
				cC.await();
			}
			System.out.println(Thread.currentThread().getName());
			Thread.sleep(1000);
			flag = "A";
			cA.signal();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
}
